<template>
  <div class="item-manage-container">
    <div v-show="isShowTree" class="item-manage-container-left">
      <div style="padding: 5px 8px">
        <span :class="isSelectArea ? 'tree-select' : 'tree-select--none'" @click="isSelectArea = true">区划</span>
        <span :class="!isSelectArea ? 'tree-select' : 'tree-select--none'" @click="isSelectArea = false">事项目录</span>
      </div>
      <el-tree
        v-show="isSelectArea"
        key="area"
        class="area-tree"
        ref="el-tree"
        :data="treeData"
        :props="defaultProps"
        :default-expanded-keys="defaultExpandedKeys"
        node-key="key"
        highlight-current
        accordion
        @node-click="nodeClick"
        :current-node-key="formInline.areaCode"
      >
        <span class="custom-tree-node" slot-scope="{ data }">
          <img v-if="data.type === 'area'" class="custom-tree-node-img" src="@/assets/img/place.png" />
          <img v-else class="custom-tree-node-img" src="@/assets/img/house.png" />
          <span>{{ data.value }}</span>
        </span>
      </el-tree>
      <el-tree
        v-show="!isSelectArea"
        key="item"
        class="area-tree"
        ref="catalog-tree"
        :data="catalogTreeData"
        :props="defaultCatalogProps"
        :default-expanded-keys="[catalogTreeId]"
        node-key="id"
        highlight-current
        accordion
        @node-click="catalogNodeClick"
        :current-node-key="catalogTreeId"
      >
        <span class="custom-tree-node" slot-scope="{ data }">
          <img v-if="data.treeType === 'DEPT'" class="custom-tree-node-img" src="@/assets/img/house.png" />
          <img v-else class="custom-tree-node-catalog-img" :src="`img/itemManage/${typeIconMap[data.type]}.png`" />
          <el-tooltip class="item" effect="dark" :content="data.name" placement="top-start" :open-delay="500">
            <span>{{ data.name }}</span>
          </el-tooltip>
        </span>
      </el-tree>
    </div>
    <div v-show="isShowTree" class="menu-in" @click="handleMenu">
      <i class="el-icon-caret-left" style="padding-right: 4px"></i>
      <span>收起目录</span>
    </div>
    <div v-show="!isShowTree" class="menu-out" @click="handleMenu">
      <i class="el-icon-caret-right" style="padding-right: 4px"></i>
      <span>展开目录</span>
    </div>
    <div class="item-manage-container-right">
      <div class="page-header">
        <div class="page-header-title">
          正在操作：
          <template v-for="(item, index) in operList">
            <span :key="item.name + item.id">{{ index === 0 ? '' : ' / ' }}</span>
            <span class="oper-label" @click="turnToOper(item, index)" :key="item.id">
              {{ item.name }}
            </span>
          </template>
        </div>
        <div class="page-header-button flex-center">
          <el-button :type="showType === 'icon' ? 'primary' : ''" @click="changeShowType('icon')">
            <div class="flex-center">
              <i class="iconfont icon-tubiao"></i>
              图标展示
            </div>
          </el-button>
          <el-button :type="showType === 'table' ? 'primary' : ''" @click="changeShowType('table')">
            <div class="flex-center">
              <i class="iconfont icon-table"></i>
              列表展示
            </div>
          </el-button>
        </div>
      </div>
      <div class="context search-container">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-row>
            <el-col :span="24">
              <el-form-item style="margin-right: 60px" label="名称：">
                <el-input v-model="formInline.name" placeholder="请输入名称" clearable></el-input>
              </el-form-item>
              <el-form-item style="margin-right: 60px" label="编码：">
                <el-input v-model="formInline.coding" placeholder="请输入编码" clearable></el-input>
              </el-form-item>
              <el-form-item style="margin-right: 60px" label="事项类型：">
                <el-select v-model="formInline.typeId" placeholder="请选择事项类型" clearable>
                  <el-option
                    v-for="item in eventTypeList"
                    :label="item.item_text"
                    :value="item.item_value"
                    :key="item.item_value"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item style="float: right">
                <el-button type="primary" @click="onSearch('click')" style="width: 120px">搜索</el-button>
                <el-button
                  v-show="formInline.parentType === 'ROOT'"
                  type="primary"
                  @click="addCatalog('新建事项基本目录')"
                  style="width: 150px"
                >
                  新建事项基本目录
                </el-button>
                <el-button
                  v-show="['CATALOGUE_MAIN', 'CATALOGUE_ITEM'].includes(formInline.parentType)"
                  type="primary"
                  @click="addCatalog('新建事项基本目录子项')"
                  style="width: 180px"
                >
                  新建事项基本目录子项
                </el-button>
                <el-button
                  v-show="formInline.parentType === 'CATALOGUE_ITEM'"
                  type="primary"
                  @click="addItem('新建目录子项')"
                  style="width: 150px"
                >
                  新建实施清单
                </el-button>
                <el-button
                  v-show="formInline.parentType === 'EVENT_MAIN'"
                  type="primary"
                  @click="addItem('新建实施清单办理项')"
                  style="width: 150px"
                >
                  新建实施清单办理项
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item style="margin-right: 60px" label="状态：">
                <el-radio-group v-model="formInline.state">
                  <el-radio label="" border>全部</el-radio>
                  <el-radio :key="item.item_value" :label="item.item_value" border v-for="item in stateList">
                    {{ item.item_text }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item style="float: right">
                <el-upload
                  style="display: inline-block; padding-right: 10px"
                  action="/api/v1/event/catalogue/uploadExcel"
                  :show-file-list="false"
                  accept=".xls,.xlsx"
                  :on-success="importExcelSuccess"
                  :on-error="importExcelError"
                >
                  <el-button type="primary" plain style="width: 120px">Excel导入</el-button>
                </el-upload>
                <el-button type="primary" plain @click="exportExcel" style="width: 120px">Excel导出</el-button>
                <el-button type="success" plain @click="downTemplate" style="width: 120px">模板下载</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item style="margin-right: 60px" label="行使层级(多选)：">
                <el-checkbox-group v-model="formInline.hierarchyId">
                  <el-checkbox
                    :label="item.item_value"
                    :key="item.item_value"
                    border
                    v-for="item in exerciseHierarchyList"
                  >
                    {{ item.item_text }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item style="margin-right: 60px" label="类型：">
                <el-select v-model="formInline.type" placeholder="请选择类型" clearable>
                  <el-option
                    v-for="item in typeList"
                    :label="item.item_text"
                    :value="item.item_value"
                    :key="item.item_value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item style="float: right">
                <el-button
                  type="primary"
                  :disabled="!checkBoxGroup.length"
                  plain
                  @click="batchSubmitAudit"
                  style="width: 120px"
                >
                  批量提交审核
                </el-button>
                <el-button type="danger" :disabled="!checkBoxGroup.length" plain @click="batchDel" style="width: 120px">
                  批量删除
                </el-button>
              </el-form-item> -->
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div v-show="showType === 'table'" v-loading="loading" class="tableBox">
        <el-table
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          height="100%"
          @selection-change="handleSelectionChange"
          @row-contextmenu="openContextMenu"
        >
          <el-table-column type="selection" align="center" width="60"></el-table-column>
          <el-table-column prop="name" label="名称" show-overflow-tooltip>
            <div class="ec-name" slot-scope="scope" @dblclick="dblclick(scope.row)">
              <img class="tableBox-img" :src="`img/itemManage/${typeIconMap[scope.row.type]}.png`" />
              <span style="margin-left: 10px">{{ scope.row.name }}</span>
              <span v-show="scope.row.count" class="checkbox-info">{{ scope.row.count }}</span>
              <!-- <span class="checkbox-status" :class="'status-content status--' + scope.row.state">{{ stateMap[scope.row.state] }}</span> -->
            </div>
          </el-table-column>

          <el-table-column prop="areaCode" label="区划" width="150">
            <template slot-scope="scope">
              <span>
                {{
                  areaMap[(scope.row.data && scope.row.data.areaCode) || scope.row.areaCode] &&
                  areaMap[(scope.row.data && scope.row.data.areaCode) || scope.row.areaCode].value
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="departName" label="行使部门" width="120"></el-table-column>

          <el-table-column prop="coding" label="编码" width="150"></el-table-column>

          <el-table-column prop="hierarchyId" label="行使层级" width="320">
            <template slot-scope="scope">
              <span>
                {{
                  scope.row.exerciseAgency && scope.row.exerciseAgency.map((e) => exerciseHierarchyMap[e]).join('，')
                }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="state" label="状态" width="100">
            <template slot-scope="scope">
              <span :class="'status-content status--' + scope.row.state">{{ stateMap[scope.row.state] }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="effectiveDate" label="生效日期" width="150"></el-table-column>
          <el-table-column prop="cancellationDate" label="失效时间" width="150"></el-table-column>
        </el-table>
      </div>
      <div
        v-show="showType === 'icon'"
        v-loading="loading"
        class="iconBox"
        @contextmenu="openContextMenu(null, '', $event)"
      >
        <el-checkbox-group v-if="tableData.length" v-model="checkBoxGroup" size="small">
          <div class="checkbox-group-container">
            <el-checkbox
              v-for="item in tableData"
              :key="item.id + item.type"
              :label="item"
              @contextmenu.prevent.native="openContextMenu(item, '', $event)"
            >
              <span class="checkbox-group-container-item" @dblclick="dblclick(item)">
                <img
                  v-if="item.type === 'CATALOGUE_MAIN' || item.type === 'CATALOGUE_ITEM'"
                  class="checkbox-img"
                  :src="`img/itemManage/${typeIconMap[item.type]}.png`"
                />
                <img
                  class="checkbox-img"
                  v-else-if="item.type === 'EVENT_MAIN'"
                  :src="`img/itemManage/${typeIconMap[item.type] + (item.count ? '' : '-none')}.png`"
                />
                <img
                  class="checkbox-img"
                  v-else-if="item.type === 'EVENT_ITEM'"
                  :src="`img/itemManage/${typeIconMap[item.type] + (item.hasSituation ? '' : '-none')}.png`"
                />
                <div class="checkbox-label">{{ item.name }}</div>
                <span v-show="item.count" class="checkbox-info">{{ item.count }}</span>
                <span class="checkbox-status" :class="'status-content status--' + item.state">
                  {{ stateMap[item.state] }}
                </span>
              </span>
            </el-checkbox>
          </div>
        </el-checkbox-group>
        <div v-else class="none-data">
          <span>暂无数据</span>
        </div>
      </div>
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="formInline.current"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="formInline.size"
          layout="total, sizes, prev, pager, next"
          :total="total"
        ></el-pagination>
      </div>
    </div>
    <ul v-show="contextmenuVisible" :style="{ left: left + 'px', top: top + 'px' }" class="contextmenu">
      <li v-show="!selectItem && formInline.parentType === 'ROOT'" @click="addCatalog('新建事项基本目录')">
        新建事项基本目录
      </li>
      <li
        v-show="!selectItem && ['CATALOGUE_MAIN', 'CATALOGUE_ITEM'].includes(formInline.parentType)"
        @click="addCatalog('新建事项基本目录子项')"
      >
        新建事项基本目录子项
      </li>
      <li v-show="!selectItem && formInline.parentType === 'CATALOGUE_ITEM'" @click="addItem('新建实施清单')">
        新建实施清单
      </li>
      <li v-show="!selectItem && formInline.parentType === 'EVENT_MAIN'" @click="addItem('新建实施清单办理项')">
        新建实施清单办理项
      </li>
      <span v-show="selectItem">
        <li @click="cloneItem">克隆</li>
        <li v-show="selectState === 'D' || selectState === 'Y'" @click="editItem">编辑</li>
        <li @click="showItem">查看</li>
        <li
          @click="showItemSimple"
          v-show="selectItem && (selectItem.type == 'EVENT_MAIN' || selectItem.type == 'EVENT_ITEM')"
        >
          简单查看
        </li>
        <li v-show="selectState === 'D'" @click="submitAudit">提交审核</li>
        <li v-show="selectState === 'W' || selectState === 'Y'" @click="publish">审核发布</li>
        <li v-show="selectState === 'N'" @click="takeEffect">生效</li>
        <li v-show="selectState !== 'N'" @click="loseEffect">失效</li>
        <li @click="merge">多选合并</li>
        <li @click="history">历史</li>
        <li
          @click="showSituation"
          v-show="selectItem && (selectItem.type == 'EVENT_MAIN' || selectItem.type == 'EVENT_ITEM')"
        >
          情形管理
        </li>
        <li @click="showMIndMap">查看脑图</li>
        <li @click="delCatalogue">删除</li>
      </span>
    </ul>
    <!-- 实施清单 -->
    <implementList
      :visible.sync="implementList.visible"
      :handleType="implementList.handleType"
      :parentObj="spaceItem"
      :areaMap="areaMap"
      :operList="operList"
      :eventTypeMap="eventTypeMap"
      :exerciseHierarchyMap="exerciseHierarchyMap"
      :eicTemplet="implementList.eicTemplet"
      :selectItem="selectItem"
      @success="onSearch"
    />
    <!-- 实施清单 -->
    <!-- 实施清单提交审核 -->
    <implementListCheck
      :visible.sync="implementList.checkVisible"
      :checkData="selectItem"
      :areaCode="departAreaCode"
      :isPublish="implementList.isPublish"
      @success="onSearch"
    />
    <publishCatalog :visible.sync="publishCatalogVisible" :checkData="selectItem" @success="onSearch" />
    <!-- 实施清单提交审核 -->
    <!-- 实施清单历史 -->
    <implementListHistory ref="implementListHistory" :selectItem="selectItem" />
    <!-- 实施清单历史 -->
    <history ref="history" :selectItem="selectItem" />
    <newCatalog
      :type="catalogType"
      :title="dialogTitle"
      :parentEcId="(spaceItem && spaceItem.id) || ''"
      :eventTypeList="eventTypeList"
      :eventTypeMap="eventTypeMap"
      :exerciseHierarchyList="exerciseHierarchyList"
      :exerciseHierarchyMap="exerciseHierarchyMap"
      :treeData="treeData"
      :areaCode="formInline.areaCode"
      :deptId="deptId"
      :areaMap="areaMap"
      :selectItem="selectItem"
      :spaceItem="spaceItem"
      :visible="newCatalogVisible"
      @cancel="cancelCatalog"
    />
    <insureExamine ref="insureExamine" :selectItem="selectItem" />
    <brainMap ref="brainMap" />
    <situationManage ref="situationManage" />
  </div>
</template>

<script>
  import axios from 'axios';
  import implementList from '@/components/implementList';
  import implementListCheck from '@/components/implementListCheck';
  import history from './components/history.vue';
  import implementListHistory from './components/implementListHistory.vue';
  import newCatalog from './components/newCatalog.vue';
  import publishCatalog from './components/publishCatalog.vue';
  import insureExamine from './components/insureExamine';
  import brainMap from '@/components/BrainMap';
  import situationManage from './components/situationManage';
  import {
    getCatalogueHome,
    getCatalogueSearch,
    getAreaDepartTree,
    batchAudit,
    approval,
    invalid,
    takeEffect,
    delCatalogue,
    merge,
    getCatalogueTree,
    batchDel
  } from '@/api/itemManage';
  import { queryDict } from '@/api/common';

  const typeIconMap = {
    CATALOGUE_MAIN: 'folder-none', //目录_主项
    CATALOGUE_ITEM: 'folder', //目录_子项
    EVENT_MAIN: 'list', //事项主项
    EVENT_ITEM: 'item' //事项子项  不可以展开
  };
  export default {
    components: {
      implementList,
      implementListCheck,
      history,
      newCatalog,
      publishCatalog,
      insureExamine,
      brainMap,
      implementListHistory,
      situationManage
    },
    data() {
      return {
        catalogTreeId: '',
        isSelectArea: true,
        typeIconMap,
        operList: [], //正在处理数组
        tableData: [],
        catalogTreeData: [],
        catalogTreeMap: {},
        searchType: 'parent',
        deptId: '',
        departAreaCode: '',
        node: {
          key: '',
          name: '',
          type: ''
        },
        formInline: {
          areaCode: '510000000000',
          departId: '',
          coding: '', //基本编码
          name: '',
          hierarchyId: [],
          state: '',
          typeId: '', //事项类型
          type: '', //类型
          parentType: 'ROOT',
          parentId: '',
          size: 20,
          current: 1,
          dirType: 'ROOT' //CATALOGUE_ITEM,CATALOGUE_MAIN,EVENT_ITEM,EVENT_MAIN,ROOT
        },
        total: 0,
        isShowTree: false, //是否显示目录树
        contextmenuVisible: false, //是否显示右键菜单
        loading: false, //是否分页数据加载中
        newCatalogVisible: false, //新建目录
        publishCatalogVisible: false, //新建目录
        left: 0,
        top: 0,
        currentPage: 1,
        treeData: [],
        defaultExpandedKeys: [],
        defaultProps: {
          children: 'children',
          label: 'value'
        },
        defaultCatalogProps: {
          children: 'children',
          label: 'name'
        },
        checkBoxGroup: [], //批量选中数组
        showType: 'icon',
        catalogType: 'new',
        dialogTitle: '',
        selectItem: null, //右键选中的项
        spaceItem: null, //双击选中的项
        // 实施清单数据
        implementList: {
          visible: false, //实施清单是否显示
          checkVisible: false, // 提交审核是否显示
          handleType: '', // 操作类型，clone克隆、edit编辑、scan查看
          isPublish: false, // 是否为审核发布
          eicTemplet: 1 //1是详细类型，2是简单类型
        },
        areaMap: {},
        stateList: [],
        stateMap: {
          N: '失效',
          Y: '生效'
        },
        typeList: [
          { item_text: '基本目录', item_value: 'CATALOGUE' },
          { item_text: '实施清单', item_value: 'EVENT' }
        ], //类型
        catalogueList: [], //目录类型
        eventTypeList: [], //事项类型
        eventTypeMap: {}, //事项类型
        exerciseHierarchyList: [], //行驶层级
        exerciseHierarchyMap: {}
      };
    },
    watch: {
      contextmenuVisible(value) {
        if (value) {
          document.body.addEventListener('click', this.closeContextMenu);
        } else {
          document.body.removeEventListener('click', this.closeContextMenu);
        }
      }
    },
    computed: {
      selectState() {
        return (this.selectItem && this.selectItem.state) || '';
      }
    },
    mounted() {
      this.searchByParentId();
      this.getAreaDepartTree(); //获取区域信息
      this.getExerciseHierarchy(); //获取行驶层级值表
      this.getEventTypeList(); //获取行驶层级值表
      this.getEventStateList(); //获取行驶层级值表
      this.getCatalogueList(); //获取目录值表
      this.getCatalogueTree(); //获取目录值表
    },
    methods: {
      turnToOper(item, index) {
        this.operList.splice(index + 1, this.operList.length - index + 1);
        this.formInline.parentType = item.type;
        this.formInline.parentId = item.id;
        this.formInline.current = 1;
        this.searchType = 'parent';
        this.spaceItem = item;
        this.searchByParentId();
        this.deptId = item.deptId || this.formInline.departId;
      },
      dblclick(item) {
        if (['CATALOGUE_MAIN', 'CATALOGUE_ITEM', 'EVENT_MAIN'].includes(item.type)) {
          if (item.state !== 'Y') {
            this.$message.warning('在用状态才能双击进入！');
            return;
          }
          this.formInline.parentType = item.type;
          this.formInline.parentId = item.id;
          // 增加一个目录id
          this.formInline.ecId = item.ecId;
          this.formInline.current = 1;
          const obj = Object.assign({}, item, item.data);
          this.operList.push(obj);
          this.deptId = obj.deptId || '';
          this.searchType = 'parent';
          this.spaceItem = obj;
          this.searchByParentId();
        } else {
          this.$message.warning('该类型不支持双击操作！');
        }
      },
      //事项类型
      async getCatalogueList() {
        const { data } = await queryDict({
          dict: 'event'
        });
        if (data.success) {
          this.catalogueList = data.result;
        }
      },
      //事项类型
      async getCatalogueTree() {
        const { data } = await getCatalogueTree();
        if (data.success) {
          this.catalogTreeData = data.result;
          this.catalogTreeMap = this.transformcatalogTreeMap(data.result);
        }
      },
      transformcatalogTreeMap(treeData) {
        const tempMap = {};
        function transform(data, departAreaCode = '') {
          data.forEach((e) => {
            let tempDepartAreaCode = e.treeType === 'DEPT' ? e.areaCode : departAreaCode;
            tempMap[e.id] = {
              deptId: e.treeType === 'DEPT' ? e.deptId : e.departId,
              // deptName: e.deptName,
              id: e.id,
              areaCode: tempDepartAreaCode
            };
            if (e.children && e.children.length) {
              transform(e.children, tempDepartAreaCode);
            }
          });
        }
        transform(treeData, [], []);
        return tempMap;
      },
      //事项类型
      async getEventTypeList() {
        const { data } = await queryDict({
          dict: 'event_type'
        });
        if (data.success) {
          this.eventTypeList = data.result;
          const tempMap = {};
          data.result.forEach((e) => {
            tempMap[e.item_value] = e.item_text;
          });
          this.eventTypeMap = tempMap;
        }
      },
      //事项状态
      async getEventStateList() {
        const { data } = await queryDict({
          dict: 'matters_state'
        });
        if (data.success) {
          this.stateList = data.result;
          const tempMap = {};
          data.result.forEach((e) => {
            tempMap[e.item_value] = e.item_text;
          });
          this.stateMap = tempMap;
        }
      },
      //行驶层级 exercise_hierarchy
      async getExerciseHierarchy() {
        const { data } = await queryDict({
          dict: 'exercise_hierarchy'
        });
        if (data.success) {
          this.exerciseHierarchyList = data.result;
          const tempMap = {};
          data.result.forEach((e) => {
            tempMap[e.item_value] = e.item_text;
          });
          this.exerciseHierarchyMap = tempMap;
        }
      },
      // 不分层级查询
      onSearch(type) {
        this.checkBoxGroup = [];
        //点击查询
        if (type === 'click') {
          this.formInline.current = 1;
          this.searchType = 'click';
          this.operList = this.operList.length ? [this.operList[0]] : [];
          this.spaceItem = this.operList[0];

          this.deptId = this.formInline.departId;
        }

        if (this.searchType === 'click') {
          this.fetchDataList();
        } else {
          this.searchByParentId();
        }
      },
      // 根据层级查询
      async searchByParentId() {
        this.loading = true;

        let { areaCode, size, current, parentType, parentId, departId } = this.formInline;
        const { data } = await getCatalogueHome({ areaCode, size, current, parentType, parentId, departId });
        if (data.code === 200) {
          const { current, size, total, records } = data.result || {};
          this.tableData = records || [];
          this.formInline.current = current;
          this.formInline.size = size;
          this.total = total;
          this.loading = false;
        } else {
          this.loading = false;
        }
      },
      // 获取表单列表
      async fetchDataList() {
        this.loading = true;

        let { areaCode, name, coding, hierarchyId, state, typeId, dirType, parentId, size, current, type, departId } =
          this.formInline;
        const { data } = await getCatalogueSearch({
          areaCode,
          name,
          coding,
          hierarchyId,
          type,
          state,
          parentId,
          typeId,
          departId,
          dirType,
          size,
          current
        });
        if (data.code === 200) {
          const { current, size, total, records } = data.result || {};
          this.tableData = records || [];
          this.formInline.current = current;
          this.formInline.size = size;
          this.total = total;
          this.loading = false;
        } else {
          this.loading = false;
        }
      },
      catalogNodeClick({ id, name, type, treeType, departId = '', areaCode }) {
        this.formInline.pageNum = 1;
        this.catalogTreeId = id;
        if (treeType === 'DEPT') {
          this.spaceItem = {
            areaCode,
            departName: this.areaMap[id] && this.areaMap[id].value
          };
          this.formInline.areaCode = areaCode;
          this.formInline.departId = id;
          this.deptId = id;
          this.formInline.parentType = 'ROOT';
          this.formInline.parentId = '';
        } else {
          let tempAreaCode = this.catalogTreeMap[departId].areaCode;
          this.spaceItem = {
            areaCode: tempAreaCode,
            departName: this.areaMap[departId] && this.areaMap[departId].value
          };
          this.formInline.areaCode = tempAreaCode;
          this.formInline.departId = departId;
          this.deptId = departId;
          this.formInline.parentType = type;
          this.formInline.parentId = id;
        }
        this.operList = [
          {
            id: id,
            ecId: id,
            deptId: '', //部门ID
            name: name,
            type: 'ROOT'
          }
        ];
        this.onSearch();
      },
      nodeClick(node) {
        const tempNode = this.areaMap[node.key];
        this.departAreaCode = tempNode.departAreaCode;
        this.formInline.pageNum = 1;
        this.formInline.parentId = '';
        if (tempNode.type === 'area') {
          this.formInline.areaCode = node.key;
          this.formInline.departId = '';
          this.deptId = '';
        } else {
          this.formInline.areaCode = tempNode.departAreaCode;
          this.formInline.departId = node.key;
          this.deptId = node.key;
        }
        this.formInline.parentType = 'ROOT';
        this.formInline.parentId = '';
        this.node = {
          key: node.key,
          name: node.value,
          type: node.type
        };
        this.operList = [
          {
            id: '',
            ecId: '',
            deptId: '', //部门ID
            name: node.value,
            type: 'ROOT'
          }
        ];
        this.onSearch();
      },
      handleSizeChange(val) {
        this.formInline.size = val;
        this.onSearch();
      },
      handleCurrentChange(val) {
        this.formInline.current = val;
        this.onSearch();
      },
      handleSelectionChange(val) {
        this.checkBoxGroup = val;
      },
      handleMenu() {
        this.isShowTree = !this.isShowTree;
      },
      changeShowType(type) {
        if (this.showType === type) return;
        else {
          this.showType = type;
          //清空多选项
          this.checkBoxGroup = [];
        }
      },
      closeContextMenu() {
        this.contextmenuVisible = false;
      },
      openContextMenu(item, column, e) {
        e.stopPropagation();
        e.preventDefault();
        const menuMinWidth = 105;
        const menuMinHieght = item ? 300 : 30;
        const offsetLeft = this.$el.getBoundingClientRect().left; // container margin left
        const offsetWidth = this.$el.offsetWidth; // container width
        const offsetHeight = this.$el.offsetHeight; // container width
        const maxLeft = offsetWidth - menuMinWidth; // left boundary
        const maxTop = offsetHeight - menuMinHieght; // left boundary
        const left = e.clientX - offsetLeft + 15; // 15: margin right
        const top = e.clientY - 90;
        this.left = left > maxLeft ? maxLeft : left;
        // 400
        this.top = top > maxTop ? maxTop : top;
        this.contextmenuVisible = true;
        this.selectItem = item; //右键选中的item
      },
      //获取区域信息
      async getAreaDepartTree() {
        // 5的树就只有自己的区划和自己的部门。4的树有自己的区划及下级区划及对应的各级部门
        let areaCode = '510000000000';
        const { data } = await getAreaDepartTree(areaCode, true);
        if (data.code === 200) {
          this.treeData = [data.result];
          let firstNode = this.treeData && this.treeData[0];
          this.defaultExpandedKeys = [firstNode.key];
          this.formInline.areaCode = firstNode.key;
          this.areaMap = this.transformAreaMap(this.treeData);
          this.node = {
            key: firstNode.key,
            name: firstNode.value,
            type: firstNode.type
          };
          this.departAreaCode = this.areaMap[firstNode.key].departAreaCode;
          this.operList = [
            {
              id: '',
              ecId: '',
              deptId: '', //部门ID
              name: firstNode.value,
              type: 'ROOT'
            }
          ];
        }
      },
      transformAreaMap(treeData) {
        const tempMap = {};
        function transform(data, prePath, preValue, departAreaCode = '') {
          data.forEach((e) => {
            let fullPath = [...prePath, e.key];
            let fullValue = [...preValue, e.value];
            let tempDepartAreaCode = e.type === 'area' ? e.key : departAreaCode;
            tempMap[e.key] = {
              value: e.value,
              key: e.key,
              type: e.type,
              departAreaCode: tempDepartAreaCode,
              fullValue,
              fullPath
            };
            if (e.children && e.children.length) {
              transform(e.children, fullPath, fullValue, tempDepartAreaCode);
            }
          });
        }
        transform(treeData, [], []);
        return tempMap;
      },
      //模板下载
      downTemplate() {
        window.open('/api/v1/event/catalogue/exportTemplate');
      },
      importExcelSuccess() {
        this.onSearch();
        this.$message.success('上传成功！');
      },
      importExcelError(e) {
        this.$message.error('上传失败！', e);
      },

      //Excel导出
      async exportExcel() {
        const params = { ...this.formInline };
        let str = '';
        for (let key in params) {
          if (params[key] !== '') {
            str += `&${key}=${params[key]}`;
          }
        }
        window.open('/api/v1/event/catalogue/exportExcel?1=1' + str);
      },

      //批量删除
      async batchDel() {
        if (this.checkBoxGroup.length === 0) {
          this.$message.warning('请先批量选择数据，再批量删除');
          return;
        }
        let ids = this.checkBoxGroup.map((e) => e.id).join(',');

        const { data } = await batchDel(ids);
        data.code === 200 && this.$message.success('批量删除成功！');
        this.onSearch();
      },
      //删除
      async delCatalogue() {
        if (this.selectItem.type === 'EVENT_MAIN' || this.selectItem.type === 'EVENT_ITEM') {
          const { data } = await axios.request({
            url: `/api/v1/event/implementation/${this.selectItem.id}`,
            method: 'delete'
          });
          data.success && this.$message.success('删除成功！');
          this.onSearch();
        } else {
          const { data } = await delCatalogue(this.selectItem.id);
          data.code === 200 && this.$message.success('删除成功！');
          this.onSearch();
        }
      },
      //批量提交审核
      async batchSubmitAudit() {
        if (this.checkBoxGroup.length === 0) {
          this.$message.warning('请先批量选择数据，再批量提交审核');
          return;
        }
        const types = new Set();
        this.checkBoxGroup.forEach((e) => {
          types.add(e.type);
        });
        if (Array.from(types).length > 1) {
          this.$message.warning('请先选择同类型数据，再批量提交审核');
          return;
        } else {
          let ids = this.checkBoxGroup.map((e) => e.id).join(',');
          const { data } = await batchAudit(ids);
          data.code === 200 && this.$message.success('批量提交审核成功！');
          this.onSearch();
        }
      },

      //新建清单
      addItem(title) {
        this.selectItem = null;
        this.implementList.visible = true;
        this.implementList.handleType = 'edit';
        this.dialogTitle = title;
      },
      //新建目录
      addCatalog(title) {
        if (!this.deptId) {
          this.$message.warning('请先选择部门或在事项目录下，再新建目录');
          return;
        }
        this.selectItem = null;
        this.dialogTitle = title;
        this.newCatalogVisible = true;
        this.catalogType = 'new';
      },
      async cancelCatalog(flag) {
        this.newCatalogVisible = false;
        if (flag) {
          this.onSearch(); //新建成功刷新列表
          await this.getCatalogueTree(); //更新目录树
          this.$refs['catalog-tree'].setCurrentKey(this.catalogTreeId);
        }
      },
      //克隆
      cloneItem() {
        if (this.selectItem.type === 'EVENT_MAIN' || this.selectItem.type === 'EVENT_ITEM') {
          this.implementList.visible = true;
          this.implementList.handleType = 'clone';
        } else {
          this.dialogTitle = this.selectItem.type === 'CATALOGUE_MAIN' ? '克隆目录' : '克隆目录子项';
          this.newCatalogVisible = true;
          this.catalogType = 'clone';
        }
      },
      //编辑
      editItem() {
        if (this.selectItem.type === 'EVENT_MAIN' || this.selectItem.type === 'EVENT_ITEM') {
          this.implementList.visible = true;
          this.implementList.handleType = 'edit';
        } else {
          this.dialogTitle = this.selectItem.type === 'CATALOGUE_MAIN' ? '编辑目录' : '编辑目录子项';
          this.newCatalogVisible = true;
          this.catalogType = 'edit';
        }
      },
      //查看
      showItem() {
        if (this.selectItem.type === 'EVENT_MAIN' || this.selectItem.type === 'EVENT_ITEM') {
          this.implementList.visible = true;
          this.implementList.handleType = 'scan';
        } else {
          this.dialogTitle = '查看目录';
          this.newCatalogVisible = true;
          this.catalogType = 'detail';
        }
      },
      // 简单查看
      showItemSimple() {
        if (this.selectItem.type === 'EVENT_MAIN' || this.selectItem.type === 'EVENT_ITEM') {
          this.implementList.visible = true;
          this.implementList.handleType = 'scan';
          this.implementList.eicTemplet = 2;
        }
      },
      //提交审核
      async submitAudit() {
        const { type, state } = this.selectItem;
        if (state !== 'D') {
          this.$message.info('请在暂存状态下提交审核');
          return;
        }
        this.$prompt('请输入提交审核原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (val) => {
            if (!val) {
              return '请输入审核原因';
            }
          }
        })
          .then(async ({ value }) => {
            if (type === 'EVENT_MAIN' || type === 'EVENT_ITEM') {
              const { data } = await axios.request({
                url: `/api/v1/event/implementation/stateApproval/${this.selectItem.id}`,
                method: 'get',
                params: {
                  reason: value
                }
              });
              data.success && this.$message.success('提交审核成功！');
            } else {
              const { data } = await approval({
                ecId: this.selectItem.id,
                reason: value
              });
              data.code === 200 && this.$message.success('提交审核成功！');
            }

            this.onSearch();
          })
          .catch(() => {});
      },
      //审核发布
      async publish() {
        if (this.selectItem.type === 'EVENT_MAIN' || this.selectItem.type === 'EVENT_ITEM') {
          // 实施清单提交审核
          this.implementList.checkVisible = true;
          this.implementList.isPublish = true;
        } else {
          this.publishCatalogVisible = true;
        }
      },
      //生效
      async takeEffect() {
        this.$prompt('请输入生效原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (val) => {
            if (!val) {
              return '请输入原因';
            }
          }
        })
          .then(async ({ value }) => {
            if (this.selectItem.type === 'EVENT_MAIN' || this.selectItem.type === 'EVENT_ITEM') {
              const { data } = await axios.request({
                url: `/api/v1/event/implementation/stateTakeEffect/${this.selectItem.id}`,
                method: 'get',
                params: {
                  reason: value
                }
              });
              data.success && this.$message.success('生效成功！');
            } else {
              const { data } = await takeEffect({
                ecId: this.selectItem.id,
                reason: value
              });
              data.code === 200 && this.$message.success('生效成功！');
            }
            this.onSearch();
          })
          .catch(() => {});
      },
      //失效
      async loseEffect() {
        this.$prompt('请输入失效原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (val) => {
            if (!val) {
              return '请输入原因';
            }
          }
        })
          .then(async ({ value }) => {
            if (this.selectItem.type === 'EVENT_MAIN' || this.selectItem.type === 'EVENT_ITEM') {
              const { data } = await axios.request({
                url: `/api/v1/event/implementation/stateInvalid/${this.selectItem.id}`,
                method: 'get',
                params: {
                  reason: value
                }
              });
              data.success && this.$message.success('失效成功！');
            } else {
              const { data } = await invalid({
                ecId: this.selectItem.id,
                reason: value
              });
              data.code === 200 && this.$message.success('失效成功！');
            }
            this.onSearch();
          })
          .catch(() => {});
      },
      // 选中项为不同类型
      isDifferentType() {
        // 当前选中的类型
        const curType = this.selectItem.type;

        const isDifferentType = this.checkBoxGroup.find((e) => {
          return e.type !== curType;
        });

        return !!isDifferentType;
      },
      //多选合并
      async merge() {
        if (this.isDifferentType()) {
          this.$message.error('请选中同类型文件合并');
          return;
        }
        if (this.checkBoxGroup.length <= 1) {
          this.$message.error('请至少选中一个文件');
          return;
        }
        let ids = this.checkBoxGroup.map((e) => e.id).join(',');
        if (this.selectItem.type === 'EVENT_MAIN' || this.selectItem.type === 'EVENT_ITEM') {
          const { data } = await await axios.request({
            url: `/api/v1/event/implementation/merge`,
            method: 'get',
            params: {
              ids
            }
          });
          data.success && this.$message.success('合并成功！');
          this.onSearch();
        } else {
          const { data } = await merge({ ecIds: this.checkBoxGroup.map((e) => e.id), masterEcId: this.selectItem.id });
          data.code === 200 && this.$message.success('合并成功！');
          this.onSearch();
        }
      },
      //历史
      history() {
        if (this.selectItem.type === 'EVENT_MAIN' || this.selectItem.type === 'EVENT_ITEM') {
          this.$refs.implementListHistory.showDialog = true;
          this.$refs.implementListHistory.initPage();
          return;
        }
        this.$refs.history.showDialog = true;
        this.$refs.history.initPage();
      },
      //查看脑图
      showMIndMap() {
        this.$refs.brainMap.showDialog = true;
        this.$refs.brainMap.initPage(this.selectItem);
      },
      //情形管理
      showSituation() {
        this.$refs.situationManage.getSituationData(this.selectItem.id);
        this.$refs.situationManage.showDialog = true;
      }
    }
  };
</script>
